package com.xy.aspect;

import com.google.gson.Gson;
import com.xy.annotation.WebLog;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

@Aspect
@Component
//@Profile({"dev", "test"})
@Slf4j
public class WebLogAspect {
    private static final String LINE_SEPARATOR = System.lineSeparator();

    /**自定义@WebLog注解为切点**/
    @Pointcut("@annotation(com.xy.annotation.WebLog)")
    public void webLog(){}

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws ClassNotFoundException {
        //开始打印请求日志
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        //获取@WebLog注解的描述信息
        String methodDescription = getAspectLogDescription(joinPoint);
        log.info("URL : {}", request.getRequestURL().toString());
        log.info("Description: {}", methodDescription);
        log.info("HTTP Method : {}", request.getMethod());
        log.info("Class Method: {}.{}", joinPoint.getSignature().getDeclaringTypeName(),joinPoint.getSignature().getName());
        log.info("Ip : {}", request.getRemoteAddr());
        log.info("Request Args : {}", new Gson().toJson(joinPoint.getArgs()));
    }

    @After("webLog()")
    public void doAfter() {
        log.info("=================== END ================");
    }

    @Around("webLog()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object result = proceedingJoinPoint.proceed();
        log.info("Response Args: {}", new Gson().toJson(result));
        log.info("Time Conusming: {} ms", System.currentTimeMillis() - startTime);
        return result;
    }

    private String getAspectLogDescription(JoinPoint joinPoint) throws ClassNotFoundException {
        String targetName = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        Class<?> aClass = Class.forName(targetName);
        Method[] methods = aClass.getMethods();
        StringBuilder description = new StringBuilder("");
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                Class[] clazzs = method.getParameterTypes();
                if (clazzs.length == args.length) {
                    description.append(method.getAnnotation(WebLog.class).description());
                    break;
                }
            }
        }
        return description.toString();
    }
}
